<template>
	<a-modal :visible="visible" :maskClosable="false" @cancel="hideModal" :width="width + 'mm'">
		<a-spin :spinning="spinning" style="min-height: 100px">
			<div id="preview_content_custom"></div>
		</a-spin>
		<template #title>
			<a-space>
				<div style="margin-right: 20px">打印预览</div>
				<a-button :loading="waitShowPrinter" type="primary" icon="printer" @click.stop="print">打印</a-button>
				<a-button type="primary" icon="printer" @click.stop="toPdf">PDF</a-button>
			</a-space>
		</template>
		<template #footer>
			<a-button key="close" type="info" @click="hideModal"> 关闭 </a-button>
		</template>
	</a-modal>
</template>

<script lang="ts">
import { defineComponent, ref } from "vue";
import { message } from "ant-design-vue";

interface HiprintTemplate {
	editingPanel?: {
		width: number;
	};
	getHtml: (data: any) => string;
	print: (data: any, options: any, callbacks: { callback: () => void }) => void;
	toPdf: (data: any, title?: string) => void;
}

export default defineComponent({
	name: "PrintPreview",
	setup() {
		const visible = ref(false);
		const spinning = ref(true);
		const waitShowPrinter = ref(false);
		const width = ref(210);
		const hiprintTemplate = ref<HiprintTemplate | null>(null);
		const printData = ref<any>(null);

		const hideModal = () => {
			visible.value = false;
		};

		const show = (template: HiprintTemplate, data: any, w: number = 210) => {
			visible.value = true;
			spinning.value = true;
			width.value = template.editingPanel ? template.editingPanel.width : w;
			hiprintTemplate.value = template;
			printData.value = data;

			setTimeout(() => {
				const previewElement = document.getElementById("preview_content_custom");
				if (previewElement && hiprintTemplate.value) {
					previewElement.innerHTML = hiprintTemplate.value.getHtml(printData.value);
				}
				spinning.value = false;
			}, 500);
		};

		const print = () => {
			if (!hiprintTemplate.value) {
				message.warning("打印模板未初始化");
				return;
			}

			waitShowPrinter.value = true;
			hiprintTemplate.value.print(
				printData.value,
				{},
				{
					callback: () => {
						waitShowPrinter.value = false;
					}
				}
			);
		};

		const toPdf = () => {
			if (!hiprintTemplate.value) {
				message.warning("打印模板未初始化");
				return;
			}
			hiprintTemplate.value.toPdf(printData.value, "打印预览PDF");
		};

		return {
			visible,
			spinning,
			waitShowPrinter,
			width,
			hiprintTemplate,
			printData,
			hideModal,
			show,
			print,
			toPdf
		};
	}
});
</script>

<style lang="less" scoped>
:deep(.ant-modal-body) {
	padding: 0;
}
:deep(.ant-modal-content) {
	margin-bottom: 24px;
}
</style>
